package com.googlecode.pacswitch;

import java.nio.channels.AsynchronousSocketChannel;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "property", namespace = ObjectFactory.NS,
    propOrder = { "nestedValue" })
public class Property {
    private String _name;
    private PString _value;
    private JAXBElement<PropertyValue> _nestedValue;

    public Property() {
    }

    public Property(final String name, final PString value) {
        _name = name;
        _value = value;
    }

    @XmlAttribute(name = "name", required = true)
    public String getName() {
        return _name;
    }

    public void setName(final String value) {
        _name = value;
    }

    @XmlAttribute(name = "value")
    public PString getValue() {
        return _value;
    }

    public void setValue(final PString value) {
        _value = value;
    }

    @XmlAnyElement(lax = true)
    public JAXBElement<PropertyValue> getNestedValue() {
        return _nestedValue;
    }

    public void setNestedValue(final JAXBElement<PropertyValue> nestedValue) {
        if (!(nestedValue.getValue() instanceof PropertyValue)) {
            throw new IllegalArgumentException("The value must be of type "
                    + PropertyValue.class.getName() + ": "
                    + nestedValue.getValue());
        }
        _nestedValue = nestedValue;
    }

    public String resolve(final PacSwitch ps,
            final AsynchronousSocketChannel clientSocket) {
        if (_value != null) {
            return _value.resolve(ps, clientSocket);
        }
        if (_nestedValue != null) {
            return _nestedValue.getValue().resolve(ps, clientSocket);
        }
        return "${" + _name + '}';
    }
}
